package com.yazi.mxz.common.service.impl;

import javax.annotation.Resource;

import com.myframework.smhj.common.exception.MyEntityNotExistsException;
import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyNoPermissionException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.db.dao.MemberDao;
import com.yazi.mxz.common.db.dao.PrizeWinDao;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.PrizeWin;
import com.yazi.mxz.common.entity.enums.PrizeType;
import com.yazi.mxz.common.entity.enums.PrizeWinStatus;
import com.yazi.mxz.common.service.PrizeWinService;


@Service("prizeWinService")
public class PrizeWinServiceImpl extends BasicService<PrizeWin> implements PrizeWinService {
	private static Logger log = LoggerFactory.getLogger(PrizeWinServiceImpl.class);

	@Resource
	PrizeWinDao prizeWinDao;
	@Resource
	MemberDao memberDao;
	
	@Override
	protected Dao<PrizeWin> getDao() {
		return prizeWinDao;
	}
	
	@Override
	public void editToConvert(long winId) throws MyException {
		log.debug("editToConvert：winId={}", winId);
		
		PrizeWin prizeWin = prizeWinDao.get(winId);
		if (null == prizeWin) {
			throw new MyEntityNotExistsException("奖品不存在");
		}
		// 
		if (prizeWin.getStatus() != PrizeWinStatus.NORMAL.ordinal()) {
			throw new MyNoPermissionException("奖品不可兑换");
		}
		
		Member member = prizeWin.getMember();
		// 更新状态
		prizeWin.setStatus(PrizeWinStatus.CONVERTED.ordinal());
		prizeWin.setUseTime(DateUtil.getTimeStamp());
		switch (PrizeType.values()[prizeWin.getType()]) {
		case CASH_COUPON:
			break;
		case INTEGRAL:
			member.setIntegral(member.getIntegral() + prizeWin.getWorth().intValue());
			break;
		case SHAKE_COUNT:
			member.setShakeCount(member.getShakeCount() + prizeWin.getWorth().intValue());
			break;
		default:
			break;
		}
		
		memberDao.merge(member);
		prizeWinDao.merge(prizeWin);
	}
	
}
